<template>
  <textarea ref="textarea"></textarea>
</template>
<script src="https://unpkg.com/tinymce-plugin/plugins/tpImportword/plugin.min.js"></script><!--引入-->
<script>
import tinymce from 'tinymce/tinymce';
import 'tinymce/skins/ui/oxide/skin';
import 'tinymce/themes/silver/theme';
import 'tinymce/icons/default/icons';
import 'tinymce/models/dom/model';
import 'tinymce/plugins/advlist';
import 'tinymce/plugins/autolink';
import 'tinymce/plugins/autosave';
import 'tinymce/plugins/code';
import 'tinymce/plugins/directionality';
import 'tinymce/plugins/fullscreen';
import 'tinymce/plugins/insertdatetime';
import 'tinymce/plugins/link';
import 'tinymce/plugins/anchor';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/media';
import 'tinymce/plugins/nonbreaking';
import 'tinymce/plugins/pagebreak';
import 'tinymce/plugins/preview';
import 'tinymce/plugins/searchreplace';
import 'tinymce/plugins/table';
import 'tinymce/plugins/visualblocks';
import 'tinymce/plugins/visualchars';
import 'tinymce/plugins/wordcount';
import 'tinymce/plugins/image';
import mammoth from "mammoth";
import {getLightPictureToken} from "@/api/file/file";

export default {
  components: {},
  props: {
    value: String,
  },
  data() {
    return {
      editor: null,
      qiniuData: {
        key: undefined,
        url: undefined,
        upload_url: undefined,
      },
    };
  },
  watch: {
    value: {
      handler() {
        this.setValue(this.value);
      },
      immediate: true,
    },
  },
  mounted() {
    tinymce
      .init({
        target: this.$refs.textarea,
        content_css: '/tinymce/skins/ui/oxide/content.css',
        language_url: '/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        plugins:
          'lists link anchor code wordcount image table visualchars visualblocks searchreplace preview pagebreak nonbreaking media insertdatetime fullscreen directionality autosave autolink advlist',
        toolbar: [
          'word | undo redo removeformat | bold italic underline strikethrough superscript subscript backcolor forecolor | numlist bullist | blocks | searchreplace fullscreen',
          'fontfamily fontsize fontsizeselect fontsizeinput | alignleft aligncenter alignright alignjustify lineheight outdent indent | link unlink image media | preview code',
        ],
        setup: (editor) => {
          editor.ui.registry.addButton('word', {
            text: 'word',
            onAction: () => {
              console.log('xxx')
              var input = document.createElement('input');
              input.type = 'file';
              input.accept = '.doc,.docx';
              // 执行上传文件操作
              input.addEventListener("change", handleFileSelect, false);

              //获取上传文件base64数据
              function arrayBufferToBase64(arrayBuffer) {
                var binary = '';
                var bytes = new Uint8Array(arrayBuffer);
                var len = bytes.byteLength;
                for (var i = 0; i < len; i++) {
                  binary += String.fromCharCode(bytes[i]);
                }
                return window.btoa(binary);
              }

              function handleFileSelect(event) {
                var file = event.target.files[0];
                //获取上传文件后缀，如果是docx格式，则使用mammoth来进行解析，
                //如果不是则访问后台，将文件传输流base64传递到后台
                //生成文件，然后用java解析doc，并返回到前台
                var extension = file.name.slice((file.name.lastIndexOf(".") - 1 >>> 0) + 2);
                if (extension === 'docx') {
                  readFileInputEventAsArrayBuffer(event, function (arrayBuffer) {
                    // var base64Data = arrayBufferToBase64(arrayBuffer);
                    // console.log(base64Data);
                    mammoth.convertToHtml({arrayBuffer: arrayBuffer})
                      .then(displayResult, function (error) {
                        console.error(error);
                      });
                  });
                } else if (extension === 'doc') {
                  readFileInputEventAsArrayBuffer(event, function (arrayBuffer) {
                    //base64文件流
                    // var base64Data = arrayBufferToBase64(arrayBuffer);
                    // var result = "后台请求";
                    // alert(result);
                    // console.log(base64Data);
                    mammoth.convertToHtml({arrayBuffer: arrayBuffer})
                      .then(displayResult, function (error) {
                        console.error(error);
                      });
                  });
                  //tinymce的set方法将内容添加到编辑器中
                  tinymce.activeEditor.setContent(result);
                }
              }

              function displayResult(result) {
                // tinymce的set方法将内容添加到编辑器中
                tinymce.activeEditor.setContent(result.value);
              }

              function readFileInputEventAsArrayBuffer(event, callback) {
                var file = event.target.files[0];
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                  var arrayBuffer = loadEvent.target.result;
                  callback(arrayBuffer);
                };
                reader.readAsArrayBuffer(file);
              }

              // 触发点击事件，打开选择文件的对话框
              input.click();
            }
          });
        },
        font_size_formats:
          '9px 10px 11px 12px 14px 16px 18px 20px 22px 24px 26px 28px 36px 42px 48px 72px',
        font_size_input_default_unit: 'px',
        images_upload_handler: (blobInfo, progress) => {
          return this.uploadImage(blobInfo, progress);
        },
        height: 500,
        promotion: false,
      })
      .then(([editor]) => {
        this.editor = editor;
        this.setValue(this.value);
        editor.on('change keyup undo redo', () => {
          this.$emit('input', editor.getContent());
        });
      });
    getLightPictureToken().then((response) => {
      this.qiniuData.key = response.data.token;
      this.qiniuData.url = response.data.url;
      this.qiniuData.upload_url = response.data.upload_url;
    })
  },
  beforeDestroy() {
    this.editor?.destroy();
  },
  methods: {
    setValue(val) {
      const oldValue = this.editor?.getContent();
      if (typeof val === 'string' && val !== oldValue) {
        this.editor?.setContent(val);
      }
    },
    uploadImage(blobInfo, progress) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', this.qiniuData.upload_url);
        xhr.upload.onprogress = (e) => {
          progress((e.loaded / e.total) * 100);
        };
        xhr.onload = () => {
          if (xhr.status === 403) {
            reject({message: 'HTTP Error: ' + xhr.status, remove: true});
            return;
          }
          if (xhr.status < 200 || xhr.status >= 300) {
            reject('HTTP Error: ' + xhr.status);
            return;
          }
          resolve(`${xhr.response.data.url}`);
        };
        xhr.onerror = () => {
          reject(
            'Image upload failed due to a XHR Transport error. Code: ' +
            xhr.status,
          );
        };
        const formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        formData.append('key', this.qiniuData.key);
        formData.append('file_type', 'image');
        xhr.responseType = 'json';
        xhr.send(formData);
      });
    },
  },
};
</script>

<style>
.tox-tinymce-aux {
  z-index: 10000 !important;
}

.tox .tox-number-input .tox-input-wrapper {
  display: none !important;
}

.tox-statusbar__branding {
  display: none !important;
}
</style>
